interface StableFingerprint {
    get: () => string;
    reset: () => void;
}

export const StableFingerprint: StableFingerprint = (() => {
    // 核心特征类型
    type CoreFeatures = {
        hardwareConcurrency: number;
        deviceMemory: number;
        webgl: string;
        fontStable: string;
        audioFingerprint: string;
    };

    // 选择稳定性最高的5项核心特征
    const CORE_FEATURES: CoreFeatures = {
        // 硬件指纹
        hardwareConcurrency: navigator.hardwareConcurrency || 0,
        deviceMemory: (navigator as any).deviceMemory || 0, // 需处理非标准API类型

        // 图形渲染指纹
        webgl: ((): string => {
            try {
                const canvas = document.createElement('canvas');
                const gl = canvas.getContext('webgl');
                if (!gl) return 'webgl_unavailable';
                return `${gl.getParameter(gl.RENDERER)}|${gl.getParameter(gl.VENDOR)}`;
            } catch {
                return 'webgl_blocked';
            }
        })(),

        // 字体指纹
        fontStable: ((): string => {
            const baseFonts = ['Arial', 'Times New Roman', 'Courier New'];
            const span = document.createElement('span');
            span.style.visibility = 'hidden';
            span.style.fontSize = '32px';
            document.body.appendChild(span);

            const detectionResults = baseFonts.map(font => {
                span.style.fontFamily = `'${font}', sans-serif`;
                return span.offsetWidth !== 0 ? 1 : 0;
            });

            document.body.removeChild(span);
            return detectionResults.join('');
        })(),

        // 音频指纹
        audioFingerprint: ((): string => {
            try {
                const context = new (window.AudioContext || (window as any).webkitAudioContext)();
                const oscillator = context.createOscillator();
                return oscillator.type;
            } catch {
                return 'audio_blocked';
            }
        })()
    };

    // 持久化存储
    const STORAGE_KEY = 'stable_fingerprint_v3';

    // 生成指纹方法
    const generateFingerprint = (): string => {
        const jsonString = JSON.stringify(CORE_FEATURES);
        return btoa(jsonString)
            .replace(/=/g, '')
            .slice(0, 32);
    };

    return {
        get: (): string => {
            try {
                const stored = localStorage.getItem(STORAGE_KEY);
                if (stored) return stored;

                const fingerprint = generateFingerprint();
                localStorage.setItem(STORAGE_KEY, fingerprint);
                return fingerprint;
            } catch (error) {
                console.error('LocalStorage access failed:', error);
                return generateFingerprint(); // 降级方案
            }
        },

        reset: (): void => {
            try {
                localStorage.removeItem(STORAGE_KEY);
            } catch (error) {
                console.error('LocalStorage removal failed:', error);
            }
        }
    };
})();
